# -*- coding: utf-8 -*-#
#-------------------------------------------------------------------------------
# 建立者:        黄周云  
# Name:         hmwk01
# Description:
# Author:       ASUS
# Date:         2019/4/13
#-------------------------------------------------------------------------------


"""
p266第二题，使用jieba库
1、文件读操作，网上找文件
2、使用jieba分词
3、把分词结果写入到一个新文件
4、采用面向对象的方法

"""

import jieba
class Fenci:
    def __init__(self):
        self.counts = {}
        self.items = []
        self.list = []
        self.word = ''
        self.key = ''

    def read_wenjian(self,wenjian):
        try:
            txtojb = open(wenjian, 'r')
        except Exception as e:
            print(e)
        txt = txtojb.read()
        words = jieba.lcut(txt)  # 返回一个列表
        for word in words:
            if word in [',',';',' ']:
                continue
            else:
                self.counts[word] = self.counts.get(word, 0) + 1
        self.items = list(self.counts.items())
        self.items.sort(key=lambda x: x[1],reverse=True)
        txtojb.close()

    def write_wenjian(self):
        xinwenjian = open('./fenci.txt', 'w+')
        for item in self.items:
            self.word,self.key = item
            self.list.append("{0:<8}={1:>5}".format(self.word, self.key)+'\n')
        xinwenjian.writelines(self.list)
        xinwenjian.close()


fenci1 = Fenci()
fenci1.read_wenjian('./words.txt')
fenci1.write_wenjian()

















